<template>
  <div class="permission-management">
    <div class="page-header">
      <h2 class="page-title">权限管理</h2>
      <div class="search-bar">
        <el-row :gutter="16" class="mb-4">
          <el-col :span="6">
            <el-input
              v-model="searchQuery"
              placeholder="请输入用户名搜索"
              class="search-input"
              :prefix-icon="Search"
            />
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="selectedRole"
              placeholder="请选择角色"
              class="role-select"
              clearable
            >
              <el-option
                v-for="role in roles"
                :key="role.value"
                :label="role.label"
                :value="role.value"
              />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="fetchAccountList">查询</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="24" class="text-right">
            <el-button type="primary" :icon="Plus" @click="handleAddUser"
              >添加用户</el-button
            >
            <el-button type="primary" :icon="Plus" @click="handleAddRole"
              >添加角色</el-button
            >
            <el-button
              v-if="hasPermissionConfigAccess"
              type="primary"
              :icon="Setting"
              @click="handlePermissionConfig"
            >
              权限配置
            </el-button>
          </el-col>
        </el-row>
      </div>
    </div>

    <el-card class="table-card">
      <el-table
        :data="filteredTableData"
        style="width: 100%"
        border
        stripe
        highlight-current-row
      >
        <el-table-column prop="username" label="姓名" min-width="120" />
        <el-table-column prop="team" label="团队" min-width="120" />
        <el-table-column prop="role" label="角色" min-width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div class="flex items-center">
              <el-button
                type="primary"
                link
                :disabled="!canAssignAccount(scope.row)"
                @click="openAssignAccountDialog(scope.row)"
              >
                分配广告账户
              </el-button>
              <el-dropdown @command="handleMoreCommand($event, scope.row)">
                <el-button type="primary" link>
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="delete">
                      <el-icon><delete /></el-icon>删除用户
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="hasPermissionPassword"
                      command="password"
                    >
                      <el-icon><delete /></el-icon>修改用户密码
                    </el-dropdown-item>
                    <el-dropdown-item command="edit">
                      <el-icon><edit /></el-icon>修改团队角色名称
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="assignedAccounts"
          label="已分配广告主账号"
          min-width="180"
        >
          <template #default="scope">
            <span class="account-count">{{ scope.row.assignedAccounts }}</span>
            <el-button
              type="primary"
              link
              @click="openAccountDetailDialog(scope.row)"
            >
              明细
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑角色弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input
            v-model="roleForm.roleName"
            maxlength="100"
            show-word-limit
            placeholder="请输入角色名称"
          />
        </el-form-item>
        <el-form-item label="部门" prop="departId">
          <el-select v-model="roleForm.departId" placeholder="请选择部门">
            <el-option
              v-for="dept in departments"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限" prop="actionIdList">
          <el-tree
            ref="permissionTreeRef"
            :data="menuTree"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            :default-checked-keys="roleForm.actionIdList"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span v-if="data.type === 'role'" class="role-tag">{{
                  data.roleName
                }}</span>
              </span>
            </template>
          </el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitRole">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限配置弹窗 -->
    <el-dialog v-model="permissionDialogVisible" title="权限配置" width="600px">
      <el-table :data="roles" style="width: 100%">
        <el-table-column prop="label" label="角色名称" />
        <el-table-column prop="value" label="角色ID" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEditPermission(scope.row)"
            >
              编辑权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <el-button @click="permissionDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 权限树弹窗 -->
    <el-dialog
      v-model="permissionTreeDialogVisible"
      :title="permissionTreeTitle"
      width="600px"
    >
      <el-tree
        v-if="menuTree.length > 0"
        ref="permissionTreeRef"
        :data="menuTree"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        :check-strictly="true"
        default-expand-all
      >
        <template #default="{ node }">
          <span class="custom-tree-node">
            <span>{{ node.label }}</span>
          </span>
        </template>
      </el-tree>
      <el-empty v-else description="暂无权限数据" />
      <template #footer>
        <el-button @click="permissionTreeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermissions"
          >保存</el-button
        >
      </template>
    </el-dialog>

    <!-- 分配广告账户弹窗 -->
    <el-dialog
      v-model="assignAccountDialogVisible"
      title="分配广告账户"
      width="1200px"
    >
      <div style="display: flex; gap: 24px">
        <!-- 左侧：可分配账户列表 -->
        <div
          style="
            flex: 1;
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 16px;
            min-width: 300px;
          "
        >
          <div
            style="
              display: flex;
              justify-content: space-between;
              margin-bottom: 12px;
            "
          >
            <el-input
              v-model="accountSearch"
              placeholder="搜索广告账户"
              size="small"
              style="width: calc(100% - 180px)"
              clearable
              @clear="handleClearSearch"
            />
            <div>
              <el-button size="small" @click="handleSelectAll">全选</el-button>
              <el-button size="small" @click="handleDeselectAll"
                >全不选</el-button
              >
            </div>
          </div>
          <el-table
            ref="availableAccountsTableRef"
            :data="filteredAvailableAccounts"
            height="320"
            style="width: 100%"
            :row-class-name="tableRowClassName"
            row-key="accountId"
            @selection-change="handleAvailableSelectionChange"
          >
            <el-table-column
              type="selection"
              width="40"
              :selectable="row => !isAccountSelected(row)"
            />
            <el-table-column prop="accountName" label="账户名" />
            <el-table-column prop="accountId" label="账户ID" />
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              :page-size="pageSize"
              :total="totalAccounts"
              small
              background
              @current-change="handlePageChange"
            />
          </div>
        </div>
        <!-- 右侧：已选账户列表 -->
        <div
          style="
            flex: 1;
            border: 1px solid #eee;
            border-radius: 4px;
            padding: 16px;
            min-width: 300px;
          "
        >
          <div
            style="
              display: flex;
              justify-content: space-between;
              margin-bottom: 8px;
            "
          >
            <div style="font-weight: bold">已选中账户</div>
            <div style="display: flex; gap: 8px; align-items: center">
              <el-input
                v-model="selectedAccountSearch"
                placeholder="搜索账户"
                clearable
                size="small"
                style="width: 200px"
              />
              <el-button size="small" @click="handleClearSelected"
                >清空所有</el-button
              >
            </div>
          </div>
          <el-table
            :data="paginatedSelectedAccounts"
            height="320"
            style="width: 100%"
          >
            <el-table-column prop="accountName" label="账户名" />
            <el-table-column prop="accountId" label="账户ID" />
            <el-table-column label="操作" width="60">
              <template #default="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="removeSelectedAccount(scope.row)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="selectedAccountsPagination.currentPage"
              v-model:page-size="selectedAccountsPagination.pageSize"
              :total="filteredSelectedAccounts.length"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              small
              @size-change="handleSelectedAccountsSizeChange"
              @current-change="handleSelectedAccountsCurrentChange"
            />
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="assignAccountDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="selectedAccounts.length === 0"
          @click="confirmAssignAccounts"
          >分配权限</el-button
        >
      </template>
    </el-dialog>

    <!-- 删除用户二次确认弹窗 -->
    <el-dialog
      v-model="deleteUserDialogVisible"
      title="确认删除用户"
      width="400px"
    >
      <div>确定要删除用户 {{ currentUser?.username }} 吗？此操作不可恢复。</div>
      <template #footer>
        <el-button @click="deleteUserDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDeleteUser">删除</el-button>
      </template>
    </el-dialog>

    <!-- 更换团队和角色弹窗（复用添加人员弹窗） -->
    <el-dialog
      v-model="editUserDialogVisible"
      title="更换团队和角色"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="username">
          <el-input
            v-model="userForm.username"
            maxlength="100"
            show-word-limit
            placeholder="请输入用户姓名"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            maxlength="100"
            show-word-limit
            placeholder="请输入登录邮箱"
            disabled
          />
        </el-form-item>
        <el-form-item label="部门" prop="departments">
          <el-select
            v-model="userForm.departments"
            placeholder="请选择用户部门"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.value"
              :label="dept.label"
              :value="dept.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="userForm.roles"
            placeholder="请选择用户角色"
            clearable
            @change="handleRoleChange"
          >
            <el-option
              v-for="role in roles"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitUser">确定</el-button>
      </template>
    </el-dialog>

    <!-- 广告账户明细弹窗 -->
    <el-dialog
      v-model="accountDetailDialogVisible"
      title="广告账户明细"
      width="600px"
    >
      <el-table
        v-loading="accountDetailLoading"
        :data="accountDetailList"
        style="width: 100%"
        border
      >
        <el-table-column prop="accountName" label="广告账户名" />
        <el-table-column prop="accountId" label="广告账户ID" />
        <el-table-column prop="authorizer" label="授权人" />
        <el-table-column prop="authDate" label="授权日期" />
      </el-table>
      <template #footer>
        <el-button @click="accountDetailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 添加用户弹窗 -->
    <el-dialog v-model="addUserDialogVisible" title="添加用户" width="500px">
      <el-form
        ref="addUserFormRef"
        :model="addUserForm"
        :rules="addUserRules"
        label-width="80px"
      >
        <el-form-item label="姓名" prop="nickName">
          <el-input
            v-model="addUserForm.nickName"
            maxlength="100"
            show-word-limit
            placeholder="请输入用户姓名"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="addUserForm.email"
            maxlength="100"
            show-word-limit
            placeholder="请输入登录邮箱"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addUserForm.password"
            type="password"
            maxlength="100"
            show-password
            placeholder="请输入密码"
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select
            v-model="addUserForm.roleId"
            placeholder="请选择用户角色"
            clearable
          >
            <el-option
              v-for="role in roles"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddUser">确定</el-button>
      </template>
    </el-dialog>

    <!-- 密码修改弹窗 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="500px">
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="80px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            maxlength="100"
            show-password
            autocomplete="new-password"
            :readonly="false"
            placeholder="请输入新密码"
            @focus="
              (e: FocusEvent) =>
                (e.target as HTMLInputElement).removeAttribute('readonly')
            "
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            maxlength="100"
            show-password
            autocomplete="new-password"
            :readonly="false"
            placeholder="请再次输入新密码"
            @focus="
              (e: FocusEvent) =>
                (e.target as HTMLInputElement).removeAttribute('readonly')
            "
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePasswordSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  getRoles,
  getAccountList,
  getDepartList,
  addUser,
  editUser,
  deleteUser,
  checkEmailExist as checkEmailExistApi,
  assignAccounts,
  getAccountDetails,
  getPermissionTree,
  savePermissions,
  bindRole,
  getAdAccountList,
  bindAdAccount,
  getMenu1List,
  getMenu2List,
  getActionList,
  createRole,
  getRolePermission,
  updateRole,
  editUserPassword
} from "@/api/permission";
import { getAdAccounts } from "@/api/promotion";
import { accountCreate } from "@/api/user";
import { hasActionPermission, getUserPermission } from "@/utils/permission";
import {
  Search,
  Plus,
  Setting,
  ArrowDown,
  Delete,
  Edit
} from "@element-plus/icons-vue";

// 使用defineProps和defineEmits解决TypeScript错误
defineProps<{}>(); // 空对象表示此组件不需要props
defineEmits<{}>(); // 空对象表示此组件不发出事件

// 角色列表
const roles = ref([]);

// 统一权限树，用于所有需要权限树的场景
const permissionTree = ref([]);
// 是否正在加载权限树
const permissionTreeLoading = ref(false);

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await getRoles();
    console.log(response, "getRoles");
    roles.value = response.map(role => ({
      label: role.roleName,
      value: role.roleId
    }));
  } catch (error) {
    console.error("获取角色列表失败:", error);
    ElMessage.error("获取角色列表失败，请刷新重试");
  }
};

// 搜索和筛选
const searchQuery = ref("");
const selectedRole = ref(null);
const tableData = ref([]);

// 获取用户列表
const fetchAccountList = async () => {
  try {
    const response = await getAccountList({
      nickName: searchQuery.value,
      roleId: selectedRole.value
    });
    // 正确映射后端字段到表格字段
    tableData.value = response.list.map(item => ({
      username: item.nickName || "", // 用户名
      email: item.email || "", // 邮箱
      team: item.departName || "", // 团队
      role: item.roleName || "", // 角色
      assignedAccounts: `${item.adAccountIdCnt || 0}个广告账户`, // 已分配广告主账号
      ...item
    }));
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败，请刷新重试");
  }
};

// 实时筛选后的表格数据
const filteredTableData = computed(() => {
  let data = tableData.value;
  return data;
});

// 部门列表
const departments = ref([]);

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const response = await getDepartList();
    departments.value = response.map(dept => ({
      label: dept.departName,
      value: dept.departId
    }));
  } catch (error) {
    console.error("获取部门列表失败:", error);
    ElMessage.error("获取部门列表失败，请刷新重试");
  }
};

// 构建完整的权限树
const fetchAllPermissionTree = async () => {
  // 避免重复加载
  if (permissionTreeLoading.value) return;
  permissionTreeLoading.value = true;

  try {
    // 1. 获取所有一级菜单
    const menu1Response = await getMenu1List();
    if (!menu1Response || !Array.isArray(menu1Response)) {
      throw new Error("获取一级菜单失败");
    }

    // 2. 临时存储整个权限树
    const fullTree = [];

    // 3. 遍历一级菜单，获取每个菜单下的二级菜单
    for (const menu1 of menu1Response) {
      const menu2Response = await getMenu2List(menu1.menu1Id);
      if (!menu2Response || !Array.isArray(menu2Response)) {
        continue; // 跳过获取失败的二级菜单
      }

      // 4. 准备一级菜单节点，以及子菜单列表
      const menu1Node = {
        id: `menu1-${menu1.menu1Id}`,
        label: menu1.menu1Name,
        type: "menu1",
        menu1Id: menu1.menu1Id,
        menu1Key: menu1.menu1Key,
        children: []
      };

      // 5. 遍历二级菜单，获取每个二级菜单下的所有操作事件
      for (const menu2 of menu2Response) {
        const actionResponse = await getActionList(menu2.menu2Id);
        if (!actionResponse || !Array.isArray(actionResponse)) {
          continue; // 跳过获取失败的操作事件
        }

        // 6. 准备二级菜单节点，以及操作事件列表
        const menu2Node = {
          id: `menu2-${menu2.menu2Id}`,
          label: menu2.menu2Name,
          type: "menu2",
          menu2Id: menu2.menu2Id,
          menu2Key: menu2.menu2Key,
          menu1Id: menu2.menu1Id,
          children: actionResponse.map(action => ({
            id: `action-${action.actionId}`,
            label: action.actionName,
            type: "action",
            actionId: action.actionId,
            actionKey: action.actionKey,
            menu2Id: action.menu2Id
          }))
        };

        // 7. 添加二级菜单到一级菜单的子菜单中
        menu1Node.children.push(menu2Node);
      }

      // 8. 添加构建好的一级菜单到权限树中
      fullTree.push(menu1Node);
    }

    // 9. 更新全局权限树
    permissionTree.value = fullTree;
    console.log("权限树构建完成:", permissionTree.value);
  } catch (error) {
    console.error("构建权限树失败:", error);
    ElMessage.error("构建权限树失败，部分功能可能受到影响");
  } finally {
    permissionTreeLoading.value = false;
  }
};

// 在组件挂载时获取所有列表数据
onMounted(() => {
  fetchRoles();
  fetchAccountList();
  fetchDepartments();
  fetchAllPermissionTree(); // 加载并构建完整权限树
});

// 用户表单
const userFormRef = ref<FormInstance>();
const dialogVisible = ref(false);
const dialogTitle = ref("添加角色");
const roleFormRef = ref<FormInstance>();
const roleForm = ref({
  roleName: "",
  departId: "",
  actionIdList: [] as string[]
});

// 添加userForm定义
const userForm = ref({
  username: "",
  email: "",
  departments: "",
  roles: ""
});

// 表单验证规则
const rules = {
  roleName: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { max: 100, message: "角色名称过长", trigger: "blur" }
  ],
  departId: [{ required: true, message: "请选择部门", trigger: "change" }],
  actionIdList: [{ required: true, message: "请选择权限", trigger: "change" }]
};

// 权限配置
const permissionDialogVisible = ref(false);
const permissionTreeDialogVisible = ref(false);
const menuTree = ref([]);
const checkedKeys = ref([]);
const currentEditRole = ref(null);
const defaultProps = {
  children: "children",
  label: "label",
  id: "id",
  type: "type"
};

// 权限树引用
const permissionTreeRef = ref();

// 打开权限配置弹窗
const handlePermissionConfig = () => {
  permissionDialogVisible.value = true;
};

// 打开权限树弹窗
const handleEditPermission = async role => {
  currentEditRole.value = role;

  // 检查全局权限树是否已经构建完成
  if (permissionTree.value.length === 0 && !permissionTreeLoading.value) {
    // 如果权限树还未构建且不在加载中，则构建权限树
    await fetchAllPermissionTree();
  }

  // 等待权限树构建完成
  if (permissionTreeLoading.value) {
    ElMessage.info("正在加载权限树，请稍候...");
    // 等待权限树加载完成
    const checkInterval = setInterval(() => {
      if (!permissionTreeLoading.value) {
        clearInterval(checkInterval);
        fetchRolePermission(role.value);
        permissionTreeDialogVisible.value = true;
      }
    }, 300);
    return;
  }

  // 权限树已经构建完成，直接获取角色权限并显示弹窗
  await fetchRolePermission(role.value);
  permissionTreeDialogVisible.value = true;
};

// 获取角色权限信息并设置选中状态
const fetchRolePermission = async (roleId: number) => {
  try {
    console.log(roleId, "roleId");
    const response = await getRolePermission(roleId);
    if (!response) {
      ElMessage.error("获取角色权限数据失败");
      return;
    }

    console.log(response, "response");
    // 使用深拷贝从全局权限树复制，避免修改全局缓存
    menuTree.value = JSON.parse(JSON.stringify(permissionTree.value));

    // 如果权限树为空（极少情况），使用原始方法构建
    if (menuTree.value.length === 0) {
      console.warn("使用角色权限响应构建权限树 - 全局权限树构建可能失败");

      // 构建树结构
      menuTree.value = response.menu1List.map(menu1 => ({
        id: `menu1-${menu1.menu1Id}`,
        label: menu1.menu1Name,
        type: "menu1",
        children:
          menu1.menu2List?.map(menu2 => ({
            id: `menu2-${menu2.menu2Id}`,
            label: menu2.menu2Name,
            type: "menu2",
            children:
              menu2.actionList?.map(action => ({
                id: `action-${action.actionId}`,
                label: action.actionName,
                type: "action"
              })) || []
          })) || []
      }));
    }

    // 设置已选中的权限
    const actionIds = response.menu1List
      .flatMap(menu1 => menu1.menu2List || [])
      .flatMap(menu2 => menu2.actionList || [])
      .map(action => `action-${action.actionId}`);

    // 获取所有选中的菜单ID
    const menu1Ids = response.menu1List
      .filter(menu1 =>
        menu1.menu2List?.some(menu2 => menu2.actionList?.length > 0)
      )
      .map(menu1 => `menu1-${menu1.menu1Id}`);

    const menu2Ids = response.menu1List
      .flatMap(menu1 => menu1.menu2List || [])
      .filter(menu2 => menu2.actionList?.length > 0)
      .map(menu2 => `menu2-${menu2.menu2Id}`);

    // 合并所有需要选中的节点ID
    checkedKeys.value = [...menu1Ids, ...menu2Ids, ...actionIds];

    // 等待DOM更新后设置选中状态
    await nextTick();
    if (permissionTreeRef.value) {
      permissionTreeRef.value.setCheckedKeys(checkedKeys.value);
    }
  } catch (error) {
    console.error("获取角色权限失败:", error);
    ElMessage.error("获取权限失败，请重试");
  }
};

// 处理添加角色
const handleAddRole = async () => {
  dialogTitle.value = "添加角色";
  roleForm.value = {
    roleName: "",
    departId: "",
    actionIdList: []
  };

  // 使用全局权限树
  menuTree.value = JSON.parse(JSON.stringify(permissionTree.value));

  // 如果权限树还未加载完成，则加载权限树
  if (menuTree.value.length === 0) {
    await fetchAllPermissionTree();
    menuTree.value = JSON.parse(JSON.stringify(permissionTree.value));
  }

  dialogVisible.value = true;

  // 清空选中状态
  await nextTick();
  if (permissionTreeRef.value) {
    permissionTreeRef.value.setCheckedKeys([]);
  }
};

// 提交角色表单
const handleSubmitRole = async () => {
  if (!roleFormRef.value) return;

  try {
    await roleFormRef.value.validate();

    // 获取选中的权限节点
    const checkedNodes = permissionTreeRef.value?.getCheckedKeys() || [];
    const halfCheckedNodes =
      permissionTreeRef.value?.getHalfCheckedKeys() || [];
    const allCheckedNodes = [...checkedNodes, ...halfCheckedNodes];

    // 构建保存数据
    const saveData = {
      roleName: roleForm.value.roleName,
      departId: Number(roleForm.value.departId),
      actionIdList: allCheckedNodes
        .filter(key => key.startsWith("action-"))
        .map(key => Number(key.split("-")[1]))
    };

    await createRole(saveData);
    ElMessage.success("添加角色成功");
    dialogVisible.value = false;
    fetchRoles(); // 刷新角色列表
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败，请重试");
  }
};

// 广告账户明细
const accountDetailList = ref<any[]>([]);
const accountDetailLoading = ref(false);

// 打开广告账户明细弹窗
const openAccountDetailDialog = async (row: any) => {
  currentUser.value = row;
  accountDetailDialogVisible.value = true;
  accountDetailLoading.value = true;

  try {
    // 调用 getAdAccounts 接口获取该用户的广告账户列表
    const response = await getAdAccounts({ accountId: row.accountId });
    // 处理响应数据，设置授权人和授权日期为空
    accountDetailList.value = (response || []).map(account => ({
      accountName: account.adAccountName,
      accountId: account.adAccountId,
      authorizer: (account as any).bindAdminName || "", // 授权人，接口中无数据
      authDate: (account as any).bindAdminDate || "" // 授权日期，接口中无数据
    }));
  } catch (error) {
    console.error("获取广告账户明细失败:", error);
    ElMessage.error("获取广告账户明细失败，请重试");
    accountDetailList.value = [];
  } finally {
    accountDetailLoading.value = false;
  }
};

// 弹窗控制
const assignAccountDialogVisible = ref(false);
const deleteUserDialogVisible = ref(false);
const editUserDialogVisible = ref(false);
const accountDetailDialogVisible = ref(false);

// 当前操作用户
const currentUser = ref<any>(null);
// 分配广告账户相关
const accountSearch = ref("");
const availableAccounts = ref<any[]>([]);
const selectedAccounts = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = ref(100);
const totalAccounts = ref(0);

// 获取广告账户列表
const fetchAdAccounts = async () => {
  try {
    const response = await getAdAccountList(
      currentPage.value,
      pageSize.value,
      accountSearch.value || undefined // 使用搜索关键词作为第三个参数
    );
    console.log("广告账户列表响应:", response); // 添加日志查看实际返回的数据结构
    availableAccounts.value = response.list.map(account => ({
      accountId: account.adAccountId,
      accountName: account.adAccountName
    }));
    totalAccounts.value = response.total;
  } catch (error) {
    console.error("获取广告账户列表失败:", error);
    ElMessage.error("获取广告账户列表失败，请重试");
  }
};

// 打开弹窗时重置选中并获取数据
const openAssignAccountDialog = async (row: any) => {
  currentUser.value = row;
  assignAccountDialogVisible.value = true;
  selectedAccounts.value = [];
  try {
    // 调用 getAdAccounts 接口获取该用户的广告账户列表
    const response = await getAdAccounts({ accountId: row.accountId });
    // 处理响应数据，设置授权人和授权日期为空
    selectedAccounts.value = (response || []).map(account => ({
      accountName: account.adAccountName,
      accountId: account.adAccountId,
      authorizer: "", // 授权人，接口中无数据
      authDate: "" // 授权日期，接口中无数据
    }));
  } catch (error) {
    console.error("获取广告账户明细失败:", error);
    ElMessage.error("获取广告账户明细失败，请重试");
    selectedAccounts.value = [];
  } finally {
  }
  accountSearch.value = "";
  currentPage.value = 1;
  await fetchAdAccounts();

  // 确保清空选中状态
  nextTick(() => {
    if (availableAccountsTableRef.value) {
      if (selectedAccounts.value.length) {
        updateSelectionAfterPageChange();
      } else {
        availableAccountsTableRef.value.clearSelection();
      }
    }
  });
};

// 处理分页变化
const handlePageChange = async (page: number) => {
  currentPage.value = page;
  await fetchAdAccounts();

  // 更新页面后，恢复已选行的选中状态
  nextTick(() => {
    updateSelectionAfterPageChange();
  });
};

// 分页后更新选中状态
const updateSelectionAfterPageChange = () => {
  if (!availableAccountsTableRef.value) return;

  // 先清除所有选择
  availableAccountsTableRef.value.clearSelection();

  // 然后为当前页上已选中的行设置选中状态
  filteredAvailableAccounts.value.forEach(row => {
    if (selectedAccounts.value.some(sel => sel.accountId === row.accountId)) {
      availableAccountsTableRef.value.toggleRowSelection(row, true);
    }
  });
};

// 过滤后的可分配账户
const filteredAvailableAccounts = computed(() => {
  // 直接返回API获取的数据，不再进行本地过滤
  return availableAccounts.value;
});

// 选中可分配账户
function handleAvailableSelectionChange(selection: any[]) {
  // 只添加未被选中的账户
  selection.forEach(acc => {
    if (!selectedAccounts.value.some(sel => sel.accountId === acc.accountId)) {
      selectedAccounts.value.push(acc);
    }
  });
}

// 左侧表格引用
const availableAccountsTableRef = ref();

// 移除已选账户
function removeSelectedAccount(row: any) {
  selectedAccounts.value = selectedAccounts.value.filter(
    acc => acc.accountId !== row.accountId
  );

  // 清除左侧表格中该行的选中状态
  if (availableAccountsTableRef.value) {
    nextTick(() => {
      // 使用更可靠的方式更新选中状态：先清除所有选择，然后重新勾选已选中的项
      availableAccountsTableRef.value.clearSelection();

      // 为当前页上所有已选中的行设置选中状态
      filteredAvailableAccounts.value.forEach(row => {
        if (
          selectedAccounts.value.some(sel => sel.accountId === row.accountId)
        ) {
          availableAccountsTableRef.value.toggleRowSelection(row, true);
        }
      });
    });
  }
}

// 分配权限确认
const confirmAssignAccounts = async () => {
  try {
    const params = {
      accountId: currentUser.value.accountId,
      adAccountList: selectedAccounts.value.map(acc => ({
        adAccountId: acc.accountId,
        adAccountName: acc.accountName
      }))
    };

    await bindAdAccount(params);
    ElMessage.success("分配广告账户成功");
    assignAccountDialogVisible.value = false;
    selectedAccounts.value = [];
    fetchAccountList();
  } catch (error) {
    console.error("分配广告账户失败:", error);
    ElMessage.error("分配失败，请重试");
  }
};

// 更多按钮事件
const handleMoreCommand = (command: string, row: any) => {
  currentUser.value = row;
  if (command === "delete") {
    deleteUserDialogVisible.value = true;
  } else if (command === "edit") {
    userForm.value = {
      username: row.username || "",
      email: row.email || "",
      departments: row.departId || "",
      roles: row.roleId || ""
    };
    editUserDialogVisible.value = true;
  } else if (command === "password") {
    passwordForm.value.newPassword = "";
    passwordForm.value.confirmPassword = "";
    passwordDialogVisible.value = true;
  }
};

// 删除用户确认
const confirmDeleteUser = async () => {
  try {
    await deleteUser(currentUser.value.accountId);
    ElMessage.success("删除用户角色成功");
    deleteUserDialogVisible.value = false;
    fetchAccountList();
  } catch (error) {
    console.error("删除用户角色失败:", error);
    ElMessage.error("删除失败，请重试");
  }
};

// 判断分配广告账户按钮是否可用
const canAssignAccount = (row: any) => {
  return hasActionPermission("permission_management_addAdAccount");
};

// 权限树弹窗标题
const permissionTreeTitle = computed(() => {
  return `编辑角色"${currentEditRole.value?.label}"的权限`;
});

// 判断是否有权限配置访问权限
const hasPermissionConfigAccess = computed(() => {
  return hasActionPermission("permission_management_setPermission");
});

const hasPermissionPassword = computed(() => {
  return hasActionPermission("permission_management_modifpassword");
});

// 保存权限配置
const handleSavePermissions = async () => {
  try {
    // 获取选中的节点
    const checkedNodes = permissionTreeRef.value?.getCheckedKeys() || [];
    const halfCheckedNodes =
      permissionTreeRef.value?.getHalfCheckedKeys() || [];
    const allCheckedNodes = [...checkedNodes, ...halfCheckedNodes];

    // 构建保存数据
    const saveData = {
      roleId: currentEditRole.value.value,
      roleName: currentEditRole.value.label,
      actionIdList: allCheckedNodes
        .filter(key => key.startsWith("action-"))
        .map(key => Number(key.split("-")[1]))
    };

    await updateRole(saveData);
    ElMessage.success("保存成功");
    permissionTreeDialogVisible.value = false;
    // 刷新角色列表
    fetchRoles();
  } catch (error) {
    console.error("保存权限失败:", error);
    ElMessage.error("保存失败，请重试");
  }
};

// 提交用户表单
const handleSubmitUser = async () => {
  if (!userFormRef.value) return;

  try {
    await userFormRef.value.validate();
    // 使用bindRole接口更新用户角色信息
    const params = {
      nickName: userForm.value.username,
      accountId: currentUser.value.accountId,
      roleId: userForm.value.roles ? Number(userForm.value.roles) : 0
    };

    await bindRole(params);
    ElMessage.success("更新用户角色成功");
    editUserDialogVisible.value = false;
    fetchAccountList(); // 刷新用户列表
  } catch (error) {
    console.error("更新用户角色失败:", error);
    ElMessage.error("更新失败，请重试");
  }
};

// 处理角色变更
const handleRoleChange = async (value: number | null) => {
  try {
    // const params = {
    //   accountId: currentUser.value.accountId,
    //   roleId: value || 0
    // };
    // await bindRole(params);
    // ElMessage.success("更新用户角色成功");
    // editUserDialogVisible.value = false;
    // fetchAccountList(); // 刷新用户列表
  } catch (error) {
    console.error("更新用户角色失败:", error);
    ElMessage.error("更新失败，请重试");
    // 如果失败，回滚选择
    userForm.value.roles = currentUser.value?.roleId || "";
  }
};

const searchRoleChange = async () => {
  fetchAccountList(); // 刷新用户列表
};

// 添加用户相关
const addUserDialogVisible = ref(false);
const addUserFormRef = ref<FormInstance>();
const addUserForm = ref({
  nickName: "",
  email: "",
  password: "",
  roleId: ""
});

// 添加用户表单验证规则
const addUserRules = {
  nickName: [
    { required: true, message: "请输入用户姓名", trigger: "blur" },
    { max: 100, message: "姓名过长", trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/,
      message: "请输入正确的邮箱格式",
      trigger: "blur"
    }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" }
  ],
  roleId: [{ required: false, message: "请选择角色", trigger: "change" }]
};

// 打开添加用户弹窗
const handleAddUser = () => {
  addUserForm.value = {
    nickName: "",
    email: "",
    password: "",
    roleId: ""
  };
  addUserDialogVisible.value = true;
};

// 提交添加用户
const submitAddUser = async () => {
  if (!addUserFormRef.value) return;

  try {
    await addUserFormRef.value.validate();

    // 准备参数
    const params = {
      nickName: addUserForm.value.nickName,
      email: addUserForm.value.email,
      password: addUserForm.value.password,
      roleId: addUserForm.value.roleId
        ? Number(addUserForm.value.roleId)
        : undefined
    };

    await accountCreate(params);
    ElMessage.success("添加用户成功");
    addUserDialogVisible.value = false;
    fetchAccountList(); // 刷新用户列表
  } catch (error) {
    console.error("添加用户失败:", error);
    ElMessage.error("添加用户失败，请重试");
  }
};

// 添加灰色背景样式给已选中的行
function tableRowClassName({ row }) {
  return selectedAccounts.value.some(acc => acc.accountId === row.accountId)
    ? "selected-row"
    : "";
}

// 判断账户是否已被选中
function isAccountSelected(row: any) {
  return selectedAccounts.value.some(acc => acc.accountId === row.accountId);
}

// 防抖搜索函数
let searchTimeout: NodeJS.Timeout | null = null;

// 添加watcher监听搜索条件变化
watch(accountSearch, async () => {
  // 清除之前的定时器
  if (searchTimeout) {
    clearTimeout(searchTimeout);
  }

  // 设置新的定时器，300ms后执行搜索
  searchTimeout = setTimeout(async () => {
    // 搜索条件变化时，重置分页并重新获取数据
    currentPage.value = 1;
    await fetchAdAccounts();

    // 搜索条件变化后，确保选中状态与selectedAccounts一致
    nextTick(() => {
      updateSelectionAfterPageChange();
    });
  }, 300);
});

// 搜索输入框清空处理
async function handleClearSearch() {
  // 搜索条件被清空时，重新获取数据并更新选中状态
  currentPage.value = 1;
  await fetchAdAccounts();
  nextTick(() => {
    updateSelectionAfterPageChange();
  });
}

// 全选当前页的账户
const handleSelectAll = () => {
  // 获取当前页上未被选中的账户
  const unselectedAccounts = filteredAvailableAccounts.value.filter(
    acc => !selectedAccounts.value.some(sel => sel.accountId === acc.accountId)
  );

  // 将未选中的账户添加到已选中账户列表
  if (unselectedAccounts.length > 0) {
    selectedAccounts.value = [...selectedAccounts.value, ...unselectedAccounts];
  }

  // 更新表格选择状态
  nextTick(() => {
    updateSelectionAfterPageChange();
  });
};

// 取消选择当前页的所有账户
const handleDeselectAll = () => {
  // 获取当前页面上的账户ID列表
  const currentPageAccountIds = filteredAvailableAccounts.value.map(
    acc => acc.accountId
  );

  // 从已选中账户中移除当前页的账户
  selectedAccounts.value = selectedAccounts.value.filter(
    acc => !currentPageAccountIds.includes(acc.accountId)
  );

  // 清除表格选择
  if (availableAccountsTableRef.value) {
    availableAccountsTableRef.value.clearSelection();
  }
};

// 清空所有已选账户
const handleClearSelected = () => {
  selectedAccounts.value = [];

  // 清除表格选择
  if (availableAccountsTableRef.value) {
    availableAccountsTableRef.value.clearSelection();
  }
};

// 添加以下代码到 script 部分
const selectedAccountSearch = ref("");
const selectedAccountsPagination = ref({
  currentPage: 1,
  pageSize: 50
});

// 过滤并分页后的已选账户列表
const filteredSelectedAccounts = computed(() => {
  let filtered = selectedAccounts.value;

  // 搜索过滤
  if (selectedAccountSearch.value) {
    const searchValue = selectedAccountSearch.value.toLowerCase();
    filtered = filtered.filter(
      account =>
        account.accountName.toLowerCase().includes(searchValue) ||
        account.accountId.toString().includes(searchValue)
    );
  }

  return filtered;
});

// 分页后的已选账户列表
const paginatedSelectedAccounts = computed(() => {
  const filtered = filteredSelectedAccounts.value;
  const start =
    (selectedAccountsPagination.value.currentPage - 1) *
    selectedAccountsPagination.value.pageSize;
  const end = start + selectedAccountsPagination.value.pageSize;
  return filtered.slice(start, end);
});

// 分页处理方法
const handleSelectedAccountsSizeChange = (val: number) => {
  selectedAccountsPagination.value.pageSize = val;
  selectedAccountsPagination.value.currentPage = 1;
};

const handleSelectedAccountsCurrentChange = (val: number) => {
  selectedAccountsPagination.value.currentPage = val;
};

// 监听搜索条件变化，重置分页
watch(selectedAccountSearch, () => {
  selectedAccountsPagination.value.currentPage = 1;
});

// 监听选中账户列表变化，重置分页
watch(selectedAccounts, () => {
  selectedAccountsPagination.value.currentPage = 1;
});

// 添加以下代码到 script setup 部分，在其他 ref 变量声明附近
const passwordDialogVisible = ref(false);
const passwordForm = ref({
  newPassword: "",
  confirmPassword: ""
});

// 添加密码表单验证规则
const passwordRules = {
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const passwordFormRef = ref<FormInstance>();

// 添加提交修改密码的方法
const handlePasswordSubmit = async () => {
  console.log(currentUser.value, "currentUsercurrentUsercurrentUser");
  if (!passwordFormRef.value) return;

  try {
    await passwordFormRef.value.validate();
    await editUserPassword({
      accountId: currentUser.value.accountId,
      password: passwordForm.value.newPassword
    });

    ElMessage.success("密码修改成功");
    passwordDialogVisible.value = false;
  } catch (error) {
    console.error("修改密码失败:", error);
    ElMessage.error("修改密码失败，请重试");
  }
};
</script>

<style scoped>
.permission-management {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
  margin: 0 0 24px 0;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.search-bar {
  .el-row {
    margin-bottom: 16px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.search-input {
  width: 100%;
}

.role-select {
  width: 100%;
}

.text-right {
  text-align: right;
  .el-button {
    margin-left: 12px;
    &:first-child {
      margin-left: 0;
    }
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.account-count {
  color: #606266;
  margin-right: 8px;
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table th) {
  font-weight: 600;
  color: #1f2d3d;
}

:deep(.el-button--primary.is-link) {
  font-weight: 500;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-tree-node__content) {
  height: 40px;
}

:deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.role-tag {
  background-color: #f0f2f5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.account-label {
  color: #888;
  font-size: 12px;
}

/* 添加灰色背景样式给已选中的行 */
.selected-row {
  background-color: #f5f5f5 !important;
  color: #909399;
}
</style>
